﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using BillBook.Common;

namespace BillBook.Repository
{
    class ConfigurationFactory
    {
        private static ISessionFactory sessionFactory;
        private static readonly object lockObject = new object();

        public static ISessionFactory GetSessionFactory(string[] assembliesToAdd)
        {
            if (sessionFactory == null)
            {
                lock (lockObject)
                {
                    if (sessionFactory == null)
                    {
                        Configuration configuration = GetConfiguration();
                        LoadAssemblies(assembliesToAdd, configuration);
                        sessionFactory = configuration.BuildSessionFactory();
                    }
                }
            }
            return sessionFactory;
        }

        private static void LoadAssemblies(IEnumerable<string> assemblies, Configuration configuration)
        {
            foreach (string assembly in assemblies)
            {
                configuration.AddAssembly(assembly);
            }
        }

        private static Configuration GetConfiguration()
        {
            var config = new Configuration();
            config.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
            config.SetProperty("connection.connection_string", ConfigurationLoader.DatabaseConnectionString);
            config.SetProperty("connection.driver_class", "NHibernate.Driver.MySqlDataDriver");
            config.SetProperty("dialect", "NHibernate.Dialect.MySQLDialect");
            config.SetProperty("show_sql", "false");
            return config;
        }
    }
}